﻿using System.Linq;
using Colorful.Furniture.PermissionManagement;
using FreeSql;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;
using Volo.Abp.Auditing;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Users;

namespace Colorful.Furniture;

/// <summary>
///    基于权限控制的JSON序列化解析
/// </summary>
public class PermissionJsonContractResolver : CamelCasePropertyNamesContractResolver, ITransientDependency
{
    private readonly IBaseRepository<SysManager> _managerRepository;
    private readonly ICurrentUser _currentUser;

    public PermissionJsonContractResolver(IAbpLazyServiceProvider serviceProvider)
    {
        _managerRepository = serviceProvider.LazyGetRequiredService<IBaseRepository<SysManager>>();
        _currentUser = serviceProvider.LazyGetRequiredService<ICurrentUser>();

    }

    /// <summary>
    ///  创建属性
    /// </summary>
    /// <param name="member">成员</param>
    /// <param name="memberSerialization">成员序列化</param>
    /// <returns></returns>
    protected override JsonProperty CreateProperty(
        MemberInfo member,
        MemberSerialization memberSerialization)
    {

        var property = base.CreateProperty(member, memberSerialization);

        //判断当前的申明类型是否继承至权限定义
        if (member.DeclaringType != null && member.DeclaringType.GetInterfaces().Contains(typeof(IDefinePermissionDto)))
        {
            //TODO 进行当前用户角色字段权限的获取并进行判断
        }

        if (member.DeclaringType != null && (member.DeclaringType.IsDefined(typeof(DisableAuditingAttribute)) || member.DeclaringType.IsDefined(typeof(JsonIgnoreAttribute))))
        {
            property.ShouldSerialize = _ => false;

            return property;
        }
        if (member.IsDefined(typeof(DisableAuditingAttribute)) || member.IsDefined(typeof(JsonIgnoreAttribute)))
            property.ShouldSerialize = _ => false;

        return property;
    }
}